//
//  AppDelegate.swift
//  MacStudy
//
//  Created by 30san on 2020/9/18.
//  Copyright © 2020 Dawninest. All rights reserved.
//

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    private var statusItem: NSStatusItem?
    
//    private let mainWindow = MianWindowController(windowNibName: "MianWindowController")
    private let mainWindow = MacQQWindowController(windowNibName: "MacQQWindowController")
    
    private lazy var popver: NSPopover = {
        let popver = NSPopover()
        let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
        let vc = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier.init("BaseTableViewController")) as! NSViewController
        popver.contentViewController = vc
        popver.behavior = .transient
        return popver
    }()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // 设置statusBar
        initStatusBar()
        // 初始化windown
        mainWindow.showWindow(self)
        // 测试监听窗口关闭通知
        addObserverCloseWindow()
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // 删除statusBar
        NSStatusBar.system.removeStatusItem(statusItem!)
    }
    
    // true 关闭程序最后一个窗口时自动退出程序 或者监听 NSWindow.willCloseNotification
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }
    
    private func addObserverCloseWindow() {
        NotificationCenter.default.addObserver(self, selector: #selector(closeApplication(_:)), name: NSWindow.willCloseNotification, object: nil)
    }
    
    @objc func closeApplication(_ noti: NSNotification) {
//        print("closeApplication = \(noti)")
        if let window = noti.object as? NSWindow {
            if window == mainWindow {
                // 关闭应用
                NSApp.terminate(self)
            }
        }
    }
    
    // 应用关闭后点击Dock菜单重新打开应用
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        print("应用关闭后重新激活")
        mainWindow.window?.makeKeyAndOrderFront(self)
        return true
    }
    
    private func initStatusBar() {
        statusItem = NSStatusItem()
        let statusBar = NSStatusBar.system
        statusItem = statusBar.statusItem(withLength: NSStatusItem.squareLength)
        statusItem?.target = self
        // 不能和statusItem?.menu 同时存在
//        statusItem?.action = #selector(self.handleClick(_:))
//        statusItem?.title = "statusItem"
        statusItem?.image = NSImage(named: "icon")
//        statusItem?.button?.image = NSImage(named: "sssss")
        let menu = NSMenu(title: "bar menu")
        menu.addItem(withTitle: "退出程序", action: #selector(self.handleClickMenuItem(_:)), keyEquivalent: "X")
        menu.addItem(withTitle: "第二个", action: #selector(self.handleClickMenuItem(_:)), keyEquivalent: "")
        statusItem?.menu = menu
    }

    @objc func handleClick(_ item: NSStatusBarButton) {
        // 使用方式一
        // 激活应用到前台
//        NSRunningApplication.current.activate(options: [NSApplication.ActivationOptions.activateAllWindows, NSApplication.ActivationOptions.activateIgnoringOtherApps])
        
        // 使用方式二： 利用pop弹出视图
        popver.show(relativeTo: item.bounds, of: item, preferredEdge: NSRectEdge.minY)
    }
    
    @objc func handleClickMenuItem(_ sender: NSMenuItem) {
        if sender.keyEquivalent == "Q" {
            print("退出程序")
        }
        sender.state = sender.state == NSControl.StateValue(rawValue: 0) ? NSControl.StateValue(rawValue: 1) : NSControl.StateValue(rawValue: 0)
    }
}

